﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace nGSO.KnapsackProblem
{
	public class KpSolutionTester
	{
		public IEnumerable<KpResult> GetResult(SearchSpace _kpSpace, KpConfigElement _kpConfig)
		{
			List<KpResult> allResults = new List<KpResult>();

			foreach (Agent agent in _kpSpace.Agents)
			{
				int totalWeight = 0;
				int totalCost = 0;
                StringBuilder selectedItems = new StringBuilder();
                selectedItems.Append("[ ");

				KpResult result = new KpResult(_kpConfig.OptimizedCost, _kpConfig.MaxCapacity);

				var lastAgentHistory = agent.History[_kpConfig.Iterations - 1];
				for (int i = 0; i < _kpConfig.Dims; i++)
				{
                    int loc = (int)lastAgentHistory.Loc[i];

					totalWeight += loc * _kpConfig.Weights[i];
					totalCost += loc * _kpConfig.Costs[i];

                    selectedItems.Append(loc);
                    selectedItems.Append(",");
				}

                result.SelectedObjects = selectedItems.ToString().TrimEnd(',') + " ]";
				result.AgentId = agent.Id;
				result.TotalCost = totalCost;
				result.TotalWeight = totalWeight;
                result.Neighbours = agent.Neighbors.Count;
                

				allResults.Add(result);
			}

			return allResults;
		}
	}

	public class KpResult
	{
		private int _desigredCostResult;
		private int _maxCapacity;

		public int TotalWeight { get; set; }
		public int TotalCost { get; set; }
		public Guid AgentId { get; set; }
		public bool Ok
		{
			get
			{
				return _desigredCostResult <= TotalCost && TotalWeight <= _maxCapacity;
			}
		}

		public KpResult(int desigredCostResult, int maxCapacity)
		{
			_desigredCostResult = desigredCostResult;
			_maxCapacity = maxCapacity;
		}

		public override string ToString()
		{
			return string.Format("W: {0} - C: {1} OPTIMAL: {2} ", TotalWeight, TotalCost, Ok);
		}

        public string SelectedObjects { get; set; }

        public int Neighbours { get; set; }
    }
}
